package com.alangyun.remind.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.alangyun.remind.BaseActor;
import com.alangyun.remind.common.IdName;
import com.alangyun.remind.error.MindException;
import com.alangyun.remind.repository.StoreEngine;
import com.alangyun.remind.repository.cache.OrganCache;
import com.alangyun.remind.repository.data.OrganCaution;
import com.alangyun.remind.repository.data.OrganDataset;
import com.alangyun.remind.service.IOrganService;

@Service
public class OrganService extends BaseActor implements IOrganService {

	private void checkDataLoadOrNot() {
		if (!OrganCache.my().isLoaded()) {
			try {
				OrganDataset result = StoreEngine.openDataset(OrganDataset.class,
						new Class<?>[] { OrganCaution.class });
				OrganCache.my().addDataset(result);
			} catch (Exception ex) {
				throw new MindException("检查劳动组织预警数据的可用性失败，请确认是否已上传预警数据", ex);
			}
		}

	}

	@Override
	public List<IdName> listNames() {
		checkDataLoadOrNot();

		return OrganCache.my().listNames();
	}

	@Override
	public List<OrganCaution> listCaution(int maxSize) {

		if (maxSize <= 0 || maxSize > 25)
			maxSize = 15;

		checkDataLoadOrNot();
		return OrganCache.my().listData(maxSize);
	}

	@Override
	public List<OrganCaution> listCaution(List<Integer> ids) {

		if (ids == null || ids.size() == 0)
			return new ArrayList<>();

		int[] myids = new int[ids.size()];
		int index = 0;
		for (Integer id : ids)
			myids[index++] = id;

		checkDataLoadOrNot();
		
		return OrganCache.my().listData(myids);
	}

}
